// pages/blog-edit/blog-edit.js
const MAX_WORDS_NUM = 140
const MAX_IMG_NUM = 9
let content = '' //输入的文字内容
let userInfo = {}
const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    wordsNum: 0,
    isMaxNum: false,
    footerBottom: 0,
    imgList: [],
    selectPhoto: true //添加图片元素是否正在显示

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    userInfo = options
  },
  onInput(event) {
    let wordsNum = event.detail.value.length
    if (wordsNum >= MAX_WORDS_NUM) {
      wordsNum = `最大字数为${MAX_WORDS_NUM}`
      this.setData({
        isMaxNum: true
      })
      console.log(">>>>>", this.data.isMaxNum)
    } else {
      this.setData({
        isMaxNum: false,
      })
    }
    this.setData({
      wordsNum,
    })
    content = event.detail.value
  },
  onFocus(event) {
    this.setData({
      footerBottom: event.detail.height
    })
  },
  onBlur() {
    this.setData({
      footerBottom: 0
    })
  },
  onChooseImage() {
    let max = MAX_IMG_NUM - this.data.imgList.length
    console.log(max)

    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res)
        this.setData({
          imgList: this.data.imgList.concat(res.tempFilePaths)
        })
        if (this.data.imgList.length >= 9) {
          this.setData({
            selectPhoto: false
          })
        }
      }
    })
  },
  onDelImage(res) {
    let index = res.currentTarget.dataset.index
    this.data.imgList.splice(index, 1)
    this.setData({
      imgList: this.data.imgList,
      selectPhoto: this.data.imgList.length < 9 ? true : false
    })

    console.log(this.data.selectPhoto)
  },

  onPreviewImage(event) {
    console.log(event)
    wx.previewImage({
      urls: this.data.imgList,
      //确定你点击的是哪张图片
      current: event.target.dataset.imgsrc
    })
  },
  send() {
    let promiseArr = []
    let fildIds = []
    if (content.trim() == '') {
      wx.showModal({
        title: '请输入内容'
      })
      return
    }

    wx.showLoading({
      title: '发布中',
      mask: true
    })

    for (let i = 0, len = this.data.imgList.length; i < len; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.imgList[i]
        console.log(item)
        // 文件扩展名
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({
          cloudPath: 'blog/' + Date.now() + '-' + Math.random() * 1000000 + suffix,
          filePath: item,
          success: (res) => {
            console.log(res.fileID)
            fildIds = fildIds.concat({
              img: res.fileID,
              index: i
            })
            console.log(fildIds)
            resolve()
          },
          fail: (res) => {
            reject()
          } 
        })


      })
      promiseArr.push(p)
    }
    Promise.all(promiseArr).then((res) => {
      console.log(">>>>>>>", fildIds)
      db.collection("blog").add({
        data: {
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          content,
          img:fildIds,
           
          createTime: db.serverDate() //获取系统时间
        }
      }).then((res) => {
        console.log(res)
        wx.showToast({
          title: '发布成功',
        })
        wx.hideLoading()
        wx.navigateBack()
        //返回也页面
        let page = getCurrentPages()
        //获取所有的页面
        let prepage = page[page.length - 2]
        //获取上一级页面
        prepage.onPullDownRefresh()
        //调用上一级页面的刷新方法
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})